import 'dart:ui';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/model/config_model.dart';
import 'package:app/src/http/model/user_model.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/image_path_utils.dart';

///用户登录
class LoginRoute extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<LoginRoute> {
  _LoginPresenter presenter = _LoginPresenter();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    marginTop = px.y(180);
    var scaffold = Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.backgroundColorWithWhite,
        elevation: 0,
        title: InkWell(
          child: Container(
            padding: EdgeInsets.only(left: 12),
            child: Text(
              AppStrings.of(context).setServerAddress,
              style: TextStyle(
                  color: AppColors.themeColorWithServerAdress,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
          ),
          onTap: () {
            //跳转到服务器地址配置
            AppRouteHelper.goSerVerAddressRoute(context);
          },
        ),
        centerTitle: false,
        // leading: AppUi.getBack(context, () {
        //   //跳转到服务器地址配置
        //   AppRouteHelper.goSerVerAddressRoute(context);
        //   return true;
        // }),
        titleSpacing: 0,
      ),
      backgroundColor: AppColors.backgroundColorWithWhite,
      body: Material(
          color: AppColors.backgroundColorWithWhite, child: _body(context)),
    );
    return WillPopScope(
      child: scaffold,
      onWillPop: () async {
        return true;
      },
    );
  }

  var marginTop = 0.0;

  Widget _body(BuildContext context) {
    return Scrollbar(
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
            key: _formKey,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: px.y(100)),
                  child: Align(
                    child: Hero(
                      tag: AppUi.hero_tag_launch,
                      child: Image.asset(
                        ImagePathUtils.getPathWithImage("ic_logo_blue.png"),
                        width: px.dp(331),
                        height: px.dp(203),
                      ),
                    ),
                    alignment: Alignment.topCenter,
                  ),
                ),
                //工厂
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _factory(),
                  ),
                ),
                //用户名
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _userName(),
                  ),
                ),
                //密码
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _passWord(),
                  ),
                ),
                //登录
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: MaterialButton(
                      height: 55,
                      minWidth: px.screenWidth(),
                      onPressed: () {
                        //print('点击事件${presenter.toString()}');
                        var b = _formKey.currentState?.validate() ?? false;
                        if (b) {
                          //fixme 必须添加点击事件，不然背景色color不起作用。
                          presenter?.login(context);
                        }
                      },
                      //label 右边控件（一般为文本），不能为空
                      color: AppColors.themeColorWithServerAdress,
                      //color 按钮颜色
                      splashColor: Colors.black12,
                      //splashColor 点击时，飞溅扩散的颜色
                      //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
                      colorBrightness: Brightness.light,
                      //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(60))),
                      //shape 形状
                      textColor: Colors.white,
                      //文本默认颜色
                      child: Text(
                        AppStrings.of(context).login,
                        style: AppStyle.textStyleWithButton(),
                      ), //fixme 子控件
                    ),
                  ),
                )
              ],
            )),
      ),
    );
  }

  GlobalKey<FormState> _formKey = GlobalKey();

  //工厂地址
  TextEditingController? _factoryTextEditingController;

  Widget _factory() {
    if (_factoryTextEditingController == null) {
      _factoryTextEditingController =
          TextEditingController(text: presenter?.factory?.FactoryName);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        _factoryTextEditingController?.text =
            presenter?.factory?.FactoryName ?? "";
        //print('刷新:\t${presenter?.factory?.FactoryName}\t${_factoryTextEditingController?.text}');
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _factoryTextEditingController,
          readOnly: true,
          onTap: () {
            presenter?.getFactorygetlist(context, setState);
          },
          decoration: InputDecoration(
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_factory_name.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).factorAddressNotEmpty; //工厂不能为空
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
        );
      },
    );
  }

  //用户名
  TextEditingController? _userNameTextEditingController;

  Widget _userName() {
    if (_userNameTextEditingController == null) {
      _userNameTextEditingController =
          TextEditingController(text: presenter?.userName);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _userNameTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.userName = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).userName, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_user2.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon: (isDataMoreLength(presenter?.userName))
                ? Container(
                    width: 40,
                    height: 40,
                    child: InkWell(
                      child: Center(
                        child: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 16,
                        ),
                      ),
                      onTap: () {
                        //文本清除
                        setState(() {
                          presenter?.userName = "";
                          _userNameTextEditingController?.text = "";
                        });
                      },
                    ),
                  )
                : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).userNameNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
        );
      },
    );
  }

  //密码
  TextEditingController? _passWordTextEditingController;

  Widget _passWord() {
    if (_passWordTextEditingController == null) {
      _passWordTextEditingController =
          TextEditingController(text: presenter?.passWord);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _passWordTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.passWord = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).password, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_password.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon: (isDataMoreLength(presenter?.passWord))
                ? Container(
                    width: 40,
                    height: 40,
                    child: InkWell(
                      child: Center(
                        child: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 16,
                        ),
                      ),
                      onTap: () {
                        //文本清除
                        setState(() {
                          presenter?.passWord = "";
                          _passWordTextEditingController?.text = "";
                        });
                      },
                    ),
                  )
                : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).passwordNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
          obscureText: true,
        );
      },
    );
  }
}

class _LoginPresenter {
  //工厂
  Factory? factory = null;

  //用户名
  var userName = UserManager?.getUserInfoPersonCode() ?? "";

  //密码
  var passWord = "";

  _LoginPresenter() {
    factory = AppDataConfig.getFactory();
  }

  List<Factory>? factories = null;

  ///获取工厂（判断密钥是否正确）
  void getFactorygetlist(BuildContext context, StateSetter setState) {
    if (factories == null) {
      ConfigModel.getFactorygetlist(context, true, (value) {
        if (value == null) {
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).net_error_02); //服务器连接失败
          return;
        }
        if (value != null && value.isSuccessForData()) {
          if (value != null && value.Data != null && value.Data!.length > 0) {
            factories = value.Data;
            if (value.Data!.length == 1) {
              factory = value.Data![0];
              //默认保存第一个工厂
              AppDataConfig.saveFactory(factory);
            } else {
              _showDialogWithRollerPicker(context, setState);
            }
          }
        } else if (StringUtils.isNotEmpty(value.MsgDetail)) {
          AppDialog.showDialogWithInfo(context,
              content: value.MsgDetail); //FIXME 显示错误信息
        }
      });
    } else if (factories!.length > 1) {
      _showDialogWithRollerPicker(context, setState);
    }
  }

  _showDialogWithRollerPicker(BuildContext context, StateSetter setState) {
    AppDialog.showDialogWithRollerPicker<Factory>(context,
            datas: factories, data: factory)
        .then((value) {
      //print('=====================${value?.FactoryName}');
      if (value != null) {
        setState(() {
          factory = value;
        });
      }
    });
  }

  UserPassData? userPassData;

  ///登录
  void login(BuildContext context) {
    if (userPassData == null) {
      userPassData = UserPassData();
    }
    userPassData?.FactoryId = factory?.FactoryId;
    userPassData?.UserName = userName;
    userPassData?.PassWord = passWord;
    UserModel.login(context, true, userPassData, (value) {
      if (value.isSuccessForCode()) {
        //登录成功
        UserManager.login(context, value.Data);
      } else {
        AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
      }
    });
  }
}
